<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\exception\UploadException;
use app\common\library\Upload;
use fast\Random;
use think\addons\Service;
use think\Cache;
use think\Config;
use think\Db;
use think\Lang;
use think\Response;
use think\Validate;
use think\Session;
use app\admin\model\Guadan;
use app\admin\model\Pccart;
use app\admin\model\goods_manage\Goods;
use app\admin\model\Pcgascart;
use app\admin\model\gas\Gasset;
use app\admin\model\gas\Gasgun;
use app\admin\model\gas\Gasoil;
use Yeepay\Yop\Sdk\V1\YopConfig;
use Yeepay\Yop\Sdk\V1\YopRequest;
use Yeepay\Yop\Sdk\V1\YopRsaClient;
use Yeepay\Yop\Sdk\V1\Util\YopSignUtils;
use sandpay\HmPayClient;
use sandpay\PosHmPayClient;
use app\admin\model\Sandmerch;
use app\admin\model\exchange\Ordergas;
use app\admin\model\exchange\Ordergoods;
use app\admin\model\exchange\Orderrecharge;
use app\admin\model\exchange\OrderGasInfo;
use app\admin\model\exchange\OrderGoodsInfo;
use app\admin\model\exchange\Order;
use Yilianyun\Config\YlyConfig;
use Yilianyun\Oauth\YlyOauthClient;
use Yilianyun\Api\PrinterService;
use Yilianyun\Api\PrintService;
use app\admin\model\Printer;
use app\admin\model\system_config\Storeset;
use app\admin\model\station\Station;
use Xpyun\model\PrintRequest;
use Xpyun\service\PrintService as xpPrintService;
use Xpyun\util\NoteFormatter;
use app\common\model\StoreConfig;
use app\admin\model\Oilorder;

/**
 * Ajax异步请求接口
 * @internal
 */
class Ajax extends Backend
{

    protected $noNeedLogin = ['lang','loginuser','getDiscount'];
    protected $noNeedRight = ['*'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();

        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
    }

    /**
     * 加载语言包
     */
    public function lang()
    {

        $header = ['Content-Type' => 'application/javascript'];
        if (!config('app_debug')) {
            $offset = 30 * 60 * 60 * 24; // 缓存一个月
            $header['Cache-Control'] = 'public';
            $header['Pragma'] = 'cache';
            $header['Expires'] = gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
        }

        $controllername = input("controllername");
        //默认只加载了控制器对应的语言名，你还根据控制器名来加载额外的语言包
        $this->loadlang($controllername);
        return jsonp(Lang::get(), 200, $header, ['json_encode_param' => JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE]);
    }

    /**
     * 上传文件
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }
    }

    /**
     * 通用排序
     */
    public function weigh()
    {
        //排序的数组
        $ids = $this->request->post("ids");
        //拖动的记录ID
        $changeid = $this->request->post("changeid");
        //操作字段
        $field = $this->request->post("field");
        //操作的数据表
        $table = $this->request->post("table");
        if (!Validate::is($table, "alphaDash")) {
            $this->error();
        }
        //主键
        $pk = $this->request->post("pk");
        //排序的方式
        $orderway = strtolower($this->request->post("orderway", ""));
        $orderway = $orderway == 'asc' ? 'ASC' : 'DESC';
        $sour = $weighdata = [];
        $ids = explode(',', $ids);
        $prikey = $pk && preg_match("/^[a-z0-9\-_]+$/i", $pk) ? $pk : (Db::name($table)->getPk() ?: 'id');
        $pid = $this->request->post("pid", "");
        //限制更新的字段
        $field = in_array($field, ['weigh']) ? $field : 'weigh';

        // 如果设定了pid的值,此时只匹配满足条件的ID,其它忽略
        if ($pid !== '') {
            $hasids = [];
            $list = Db::name($table)->where($prikey, 'in', $ids)->where('pid', 'in', $pid)->field("{$prikey},pid")->select();
            foreach ($list as $k => $v) {
                $hasids[] = $v[$prikey];
            }
            $ids = array_values(array_intersect($ids, $hasids));
        }

        $list = Db::name($table)->field("$prikey,$field")->where($prikey, 'in', $ids)->order($field, $orderway)->select();
        foreach ($list as $k => $v) {
            $sour[] = $v[$prikey];
            $weighdata[$v[$prikey]] = $v[$field];
        }
        $position = array_search($changeid, $ids);
        $desc_id = isset($sour[$position]) ? $sour[$position] : end($sour);    //移动到目标的ID值,取出所处改变前位置的值
        $sour_id = $changeid;
        $weighids = array();
        $temp = array_values(array_diff_assoc($ids, $sour));
        foreach ($temp as $m => $n) {
            if ($n == $sour_id) {
                $offset = $desc_id;
            } else {
                if ($sour_id == $temp[0]) {
                    $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
                } else {
                    $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
                }
            }
            if (!isset($weighdata[$offset])) {
                continue;
            }
            $weighids[$n] = $weighdata[$offset];
            Db::name($table)->where($prikey, $n)->update([$field => $weighdata[$offset]]);
        }
        $this->success();
    }

    /**
     * 清空系统缓存
     */
    public function wipecache()
    {
        try {
            $type = $this->request->request("type");
            switch ($type) {
                case 'all':
                    // no break
                case 'content':
                    //内容缓存
                    rmdirs(CACHE_PATH, false);
                    Cache::clear();
                    if ($type == 'content') {
                        break;
                    }
                case 'template':
                    // 模板缓存
                    rmdirs(TEMP_PATH, false);
                    if ($type == 'template') {
                        break;
                    }
                case 'addons':
                    // 插件缓存
                    Service::refresh();
                    if ($type == 'addons') {
                        break;
                    }
                case 'browser':
                    // 浏览器缓存
                    // 只有生产环境下才修改
                    if (!config('app_debug')) {
                        $version = config('site.version');
                        $newversion = preg_replace_callback("/(.*)\.([0-9]+)\$/", function ($match) {
                            return $match[1] . '.' . ($match[2] + 1);
                        }, $version);
                        if ($newversion && $newversion != $version) {
                            Db::startTrans();
                            try {
                                \app\common\model\Config::where('name', 'version')->update(['value' => $newversion]);
                                \app\common\model\Config::refreshFile();
                                Db::commit();
                            } catch (\Exception $e) {
                                Db::rollback();
                                exception($e->getMessage());
                            }
                        }
                    }
                    if ($type == 'browser') {
                        break;
                    }
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        \think\Hook::listen("wipecache_after");
        $this->success();
    }

    /**
     * 读取分类数据,联动列表
     */
    public function category()
    {
        $type = $this->request->get('type', '');
        $pid = $this->request->get('pid', '');
        $where = ['status' => 'normal'];
        $categorylist = null;
        if ($pid || $pid === '0') {
            $where['pid'] = $pid;
        }
        if ($type) {
            $where['type'] = $type;
        }

        $categorylist = Db::name('category')->where($where)->field('id as value,name')->order('weigh desc,id desc')->select();

        $this->success('', '', $categorylist);
    }

    /**
     * 读取省市区数据,联动列表
     */
    public function area()
    {
        $params = $this->request->get("row/a");
        if (!empty($params)) {
            $province = isset($params['province']) ? $params['province'] : '';
            $city = isset($params['city']) ? $params['city'] : '';
        } else {
            $province = $this->request->get('province', '');
            $city = $this->request->get('city', '');
        }
        $where = ['pid' => 0, 'level' => 1];
        $provincelist = null;
        if ($province !== '') {
            $where['pid'] = $province;
            $where['level'] = 2;
            if ($city !== '') {
                $where['pid'] = $city;
                $where['level'] = 3;
            }
        }
        $provincelist = Db::name('area')->where($where)->field('id as value,name')->select();
        $this->success('', '', $provincelist);
    }

    /**
     * 生成后缀图标
     */
    public function icon()
    {
        $suffix = $this->request->request("suffix");
        $suffix = $suffix ? $suffix : "FILE";
        $data = build_suffix_image($suffix);
        $header = ['Content-Type' => 'image/svg+xml'];
        $offset = 30 * 60 * 60 * 24; // 缓存一个月
        $header['Cache-Control'] = 'public';
        $header['Pragma'] = 'cache';
        $header['Expires'] = gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
        $response = Response::create($data, '', 200, $header);
        return $response;
    }
    
       /**
     * 油枪
     *
     */
    public function getoil()
    {
    	$user_info = Session::get('admin');//获取当前登录用户信息
    	$this->agent_id = $user_info['agent_id'];
        $this->store_no = $user_info['store_no'];
        $this->admin_id = $user_info['id'];
        
    	$oil_list = \app\admin\model\gas\Gasset::where('store_no', $this->store_no)->select();
    	foreach ($oil_list as $index => $item) {
    		$item['gun'] = \app\admin\model\gas\Gasgun::where('gas_id', $item['id'])->select();
    	}
        $this->success('请求成功', '',$oil_list);
    }
    
    /**
     * 商品接口
     *
     */
    public function goodslist()
    {
    	$user_info = Session::get('admin');//获取当前登录用户信息
    	$this->agent_id = $user_info['agent_id'];
        $store_no = $user_info['store_no'];
        $this->admin_id = $user_info['id'];
    	$name = $this->request->request("name");
//  	$store_no = 1;

    	$where = [];
    	$whereOr = [];
    	if($name)
    	{
    		$where['goods_name'] = ['like', '%' . $name . '%'];
    		$whereOr['sku'] = ['like', '%' . $name . '%'];
    	}
    	$data = \app\admin\model\goods_manage\Goods::where('store_no', $store_no)->where($where)->whereOr($whereOr)->select();
//return json_encode($data);
        $this->success('请求成功', '',$data);
    }
    
     /**
     * 支付类型
     *
     */
    public function getpayway()
    {

    	$data = \app\admin\model\payment\Payway::select();

        $this->success('请求成功', '',$data);
    }
    
        /**
     * 支付方式
     *
     */
    public function getpay()
    {

    	$data = \app\admin\model\payment\Pay::select();

        $this->success('请求成功', '',$data);
    }
    
     /**
     * 会员登录接口
     *
     */
    public function loginuser()
    {
    	$user_info = Session::get('admin');//获取当前登录用户信息
    	$this->agent_id = $user_info['agent_id'];
        $store_no = $user_info['store_no'];
        $this->admin_id = $user_info['id'];
    	$mobile = $this->request->request("mobile");
    	$where = [];
    	$whereOr = [];
    	$where['store_no'] = $user_info['store_no'];
    	$gasamount = $this->request->request("gasamount");
    	$goodsamount = $this->request->request("goodsamount");
    	$gas_id = $this->request->request("gas_id");
    	if($mobile)
    	{
    		$where['mobile'] = $mobile;
    	}
    	$data = \app\admin\model\User::where('store_no', $store_no)->where($where)->whereOr($whereOr)->find();
    	$data['discount_price'] = 0;
    	
    	
        $timebool = true;
	    $llimitoil = StoreConfig::where('name','oil')->where('store_no',$store_no)->find();
	    $llimittime = StoreConfig::where('name','oil_times')->where('store_no',$store_no)->find();
	    $storeset = StoreConfig::where('name','awardoil')->where('store_no',$store_no)->find();
	    $limituser = StoreConfig::where('name','user_nolimit')->where('store_no',$store_no)->find();
	    if(!empty($llimitoil['value'])&&$gasamount>0)
	    {
	    	$oilarr = explode(',',$llimitoil['value']);
	    	$amount = json_decode($storeset['value'],true);
	    	$userarr = explode(',',$limituser['value']);
	    		
	    	if(!empty($llimittime['value']))
	    	{
	    	    $limittime =  strtotime('-'.$llimittime['value'].' hours');
	    	    $is_order = Ordergas::where('createtime','>',$limittime)->where('is_pay',2)->where('user_id',$data['id'])->where('discount_price','>',0)->where('store_no',$store_no)->count();
	    	    if($is_order)$timebool = false;
	    	      
	    	}
	    	if(in_array($data['id'],$userarr))
	    	{
	    		$timebool = true;
	    	}
	    	if(in_array($gas_id,$oilarr)&&!empty($amount)&&$timebool)
	    	{
	    		foreach ($amount as $k => $v) {
		    		if($gasamount >=$k&&$data['discount_price']<$v)$data['discount_price'] = $v;
		    	}
	    	}

       }

        $this->success('请求成功', '',$data);
    }
    
         /**
     * 获取油品优惠接口
     *
     */
    public function getDiscount()
    {
    	$user_info = Session::get('admin');//获取当前登录用户信息
    	$this->agent_id = $user_info['agent_id'];
        $store_no = $user_info['store_no'];
        $this->admin_id = $user_info['id'];
    	$user_id= $this->request->request("user_id");
    	$where = [];
    	$whereOr = [];
    	$where['store_no'] = $user_info['store_no'];
    	$gasamount = $this->request->request("gasamount");
    	$goodsamount = $this->request->request("goodsamount");
    	$gas_id = $this->request->request("gas_id");
        $type = $this->request->request("type");
    	$data['discount_price'] = 0;
    	
    	
        $timebool = true;
	    $llimitoil = StoreConfig::where('name','oil')->where('store_no',$store_no)->find();
	    $llimittime = StoreConfig::where('name','oil_times')->where('store_no',$store_no)->find();
	    $storeset = StoreConfig::where('name','awardoil')->where('store_no',$store_no)->find();
	    $limituser = StoreConfig::where('name','user_nolimit')->where('store_no',$store_no)->find();
	    if(!empty($llimitoil['value'])&&$gasamount>0)
	    {
	    	$oilarr = explode(',',$llimitoil['value']);
	    	$amount = json_decode($storeset['value'],true);
	    	$userarr = explode(',',$limituser['value']);
	    		
	    	if(!empty($llimittime['value']))
	    	{
	    	    $limittime =  strtotime('-'.$llimittime['value'].' hours');
	    	    $is_order = Ordergas::where('createtime','>',$limittime)->where('is_pay',2)->where('user_id',$user_id)->where('discount_price','>',0)->where('store_no',$store_no)->count();
	    	    if($is_order)$timebool = false;
	    	      
	    	}
	    	if(in_array($user_id,$userarr))
	    	{
	    		$timebool = true;
	    	}
	    	if(in_array($gas_id,$oilarr)&&!empty($amount)&&$timebool)
	    	{
	    		foreach ($amount as $k => $v) {
		    		if($gasamount >=$k&&$data['discount_price']<$v)$data['discount_price'] = $v;
		    	}
	    	}

       }

        $this->success('请求成功', '',$data);
    }
    
     /**
     * 插入购物车
     * 接口
     *
     */
    public function insertcart()
    {
    	$user_info = Session::get('admin');//获取当前登录用户信息
    	$this->agent_id = $user_info['agent_id'];
        $store_no = $user_info['store_no'];
        $this->admin_id = $user_info['id'];
    	$goods_id = $this->request->request("goods_id");
    	$num = $this->request->request("num");
    	$sta_id = $this->request->request("sta_id");
    	$type = $this->request->request("type");
    	$where = [];
    	if($sta_id){
    		$where['sta_id'] = $sta_id;
    	}
    	
    	$co = Pccart::where('goods_id',$goods_id)->where('store_no',$store_no)->where($where)->find();
        
        if($co)
        {
        	if($type == 1)Pccart::where('id', $co['id'])->setInc('num', $num);
        	if($type == 2)
        	{
        		
        		Pccart::where('id', $co['id'])->setDec('num', $num);
        		if(($co['num']-$num)<=0)
        			{
        				Pccart::where('goods_id',$goods_id)->where('store_no',$store_no)->where($where)->delete();
        			}
        	}
        	if($type == 3)Pccart::where('goods_id',$goods_id)->where('store_no',$store_no)->where($where)->delete();
        	$this->success('请求成功');
        }
        if($type == 1)
        {
        	$goods_info = Goods::where('id',$goods_id)->where('store_no',$store_no)->find();
    
        	Pccart::create([
	            'goods_id' => $goods_id,
	            'store_no' => $store_no,
	            'num' =>$num,
	            'name' =>$goods_info->goods_name,
	            'price' =>$goods_info->price
	        ]);
        }

        $this->success('请求成功');
    }
    
         /**
     * 删除购物车
     * 接口
     *
     */
    public function deletecart()
    {
    	$user_info = Session::get('admin');//获取当前登录用户信息
    	$this->agent_id = $user_info['agent_id'];
        $store_no = $user_info['store_no'];
        $this->admin_id = $user_info['id'];

    	Pccart::where('sta_id',0)->where('store_no',$store_no)->delete();
        $this->success('已清空');
    }
    
                 /**
     *购物车商品
     * 
     *
     */
    public function getcartlist()
    {
    	$user_info = Session::get('admin');//获取当前登录用户信息
    	$this->agent_id = $user_info['agent_id'];
        $store_no = $user_info['store_no'];
        $this->admin_id = $user_info['id'];
        $sta_id = $this->request->request("sta_id");
        $where['sta_id'] = 0;
    	$whereOr = [];
    	if($sta_id){
    		$whereOr['sta_id'] = $sta_id;
    	}
    	
    	$list = Pccart::where('store_no',$store_no)->where($where)->whereOr($whereOr)->select();
    	foreach($list as $k=>$v)
    	{
    		$v['goods_name'] = $v['name'];
    	}
    	$this->success('请求成功','',$list);
    	

        
    }
    
         /**
     * 挂单
     * 接口
     *
     */
    public function insertstation()
    {
    	$user_info = Session::get('admin');//获取当前登录用户信息
    	$this->agent_id = $user_info['agent_id'];
        $store_no = $user_info['store_no'];
        $this->admin_id = $user_info['id'];
    	$remarks = $this->request->request("remarks");  	
    	$sta_id = $this->request->request("sta_id");  
    	$where['sta_id'] = 0;
    	$whereOr = [];
    	if($sta_id){
    		$whereOr['sta_id'] = $sta_id;
    	}
    	
    	$list = Pccart::where('store_no',$store_no)->where($where)->whereOr($whereOr)->select();
    	if(!$list)$this->error('请添加商品');
    	$params['store_no']=$store_no;
    	$params['remarks']=$remarks;
    	$result = Guadan::create($params);
    	
    	foreach($list as $k=>$v)
    	{
    		Pccart::create([
	            'goods_id' => $v['goods_id'],
	            'store_no' => $store_no,
	            'sta_id' =>$result['id'],
	            'num' =>$v['num'],
	            'name' =>$v['name'],
	            'price' =>$v['price']
	        ]);
	        if($v['sta_id'] == '')Pccart::where('id',$v['id'])->delete();
    	}

        $this->success('请求成功');
    }
    
    
             /**
     * 挂单列表
     * 
     *
     */
    public function stationlist()
    {
    	$user_info = Session::get('admin');//获取当前登录用户信息
    	$this->agent_id = $user_info['agent_id'];
        $store_no = $user_info['store_no'];
        $this->admin_id = $user_info['id'];
        
    	
    	$list = Guadan::where('store_no',$store_no)->select();
    	if($list)
    	{
    		foreach($list as $k=>$v)
    	    {
    	    	$v['goods'] = Pccart::where('sta_id',$v['id'])->select();
    	    }
    	}
//return json_encode($list);
        $this->success('请求成功','',$list);
    }
    
                 /**
     *取单  作废
     * 
     *
     */
    public function getstation()
    {
    	$user_info = Session::get('admin');//获取当前登录用户信息
    	$this->agent_id = $user_info['agent_id'];
        $store_no = $user_info['store_no'];
        $this->admin_id = $user_info['id'];
        $sta_id = $this->request->request("sta_id");
        $type = $this->request->request("type");
    	if($type == 1)
    	{
    		$list = Pccart::where('sta_id',$sta_id)->select();
    		$this->success('请求成功','',$list);
    	}
    	else
    	{
    		Pccart::where('sta_id',$sta_id)->delete();
    		Guadan::where('id',$sta_id)->delete();
    		$this->success('操作成功');
    	}

        
    }
     /**
     * 插入优品购物车
     * 接口
     *
     */
    public function insertgascart()
    {
    	$user_info = Session::get('admin');//获取当前登录用户信息
    	$this->agent_id = $user_info['agent_id'];
        $store_no = $user_info['store_no'];
        $this->admin_id = $user_info['id'];
    	$gas_id = $this->request->request("gas_id");
    	$gas_gun_id = $this->request->request("gas_gun_id");
    	$amount = $this->request->request("amount");
    	$type = $this->request->request("type");

    	$co = Pcgascart::where('gas_id',$gas_id)->where('gas_gun_id',$gas_gun_id)->where('store_no',$store_no)->find();
        
        if($co)
        {
        	if($type == 1)
        	{
        		$gasset = Gasset::where('id',$gas_id)->find();
	        	if(!$gasset)$this->error('请求失败');
	            $num = round($amount/$gasset['price'],2);
        		Pcgascart::where('id', $co['id'])->update(['amount'=>$amount,'num'=>$num]);
        	}
        	if($type == 2)Pcgascart::where('id', $co['id'])->delete();
        	$this->success('请求成功');
        }
        if($type == 1)
        {
        	$gasset = Gasset::where('id',$gas_id)->find();
        	if(!$gasset)$this->error('请求失败');
            $num = round($amount/$gasset['price'],2);
        	Pcgascart::create([
	            'gas_id' => $gas_id,
	            'gas_gun_id' => $gas_gun_id,
	            'amount' =>$amount,
	            'num' =>$num,
	            'store_no' =>$store_no
	        ]);
        }

        $this->success('请求成功');
    }
              /**
     *购物车商品
     * 
     *
     */
    public function getgascartlist()
    {
    	$user_info = Session::get('admin');//获取当前登录用户信息
    	$this->agent_id = $user_info['agent_id'];
        $store_no = $user_info['store_no'];
        $this->admin_id = $user_info['id'];

    	$list = Pcgascart::where('store_no',$store_no)->select();
    	$this->success('请求成功','',$list);
    	

        
    }
    
                  /**
     *扫码支付
     * 
     *
     */
    public function manch_scan()
    {
    	$user_info = Session::get('admin');//获取当前登录用户信息
    	$this->agent_id = $user_info['agent_id'];
    	$this->admin_id = $user_info['id'];
        $store_no = $user_info['store_no'];
        $user_id = $this->request->request("user_id");
    	$sta_id = $this->request->request("sta_id");
    	$total_amount = $this->request->request("amount");
    	$gasamount = $this->request->request("gasamount");
    	$goodsamount = $this->request->request("goodsamount");
    	$authcode = $this->request->request("authcode");
    	$payType = $this->request->request("payType");
    	$gas_id = $this->request->request("gas_id");
    	$gas_gun_id = $this->request->request("gas_gun_id");
    	$discount_price = $this->request->request("discount_price");
    	$paynum = substr($authcode, 0, 2);
    	$aucount = strlen($authcode);
        $payWay = '';
        $pay = 1;
        if($paynum>=10&&$paynum<=15&&$aucount==18)
        {
        	$payWay = 'WECHAT';
        	 $pay = 1;
        }
        if($paynum>=25&&$paynum<=30&&$aucount>=16&&$aucount<=24)
        {
        	$payWay = 'ALIPAY';
        	 $pay = 2;
        }
        if($paynum>=62)
        {
        	$payWay = 'UNIONPAY';
        	$pay = 3;
        }
    	$osn = date('YmdHis') . rand(10000000,99999999);

        $paywayint = 2;
    	if(!$payWay&&$payType=='marchant_scan')$this->error('付款码无效');
    	if($payType=='pos')
    	{
    		$payWay = 'UNIONPAY';
    		$paywayint = 3;
    		$pay = 3;
    	}
    	if($payType=='cash')
    	{
    		$pay = 5;
    		$paywayint = 4;
    	}
    	$osn = date('YmdHis') . rand(10000000,99999999);

//  	$store_no = 1;
    	//商品列表
    	$gaslist = Pcgascart::where('store_no',$store_no)->select();
        $where['sta_id'] = 0;
    	$whereOr = [];
    	if($sta_id){
    		$whereOr['sta_id'] = $sta_id;
    	}
    	
    	$goodslist = Pccart::where('store_no',$store_no)->where($where)->whereOr($whereOr)->select();
    	
    	//获取渠道
    	$payinfo= \app\admin\model\payment\Payway::where('code',$payWay)->find();
    	$channel= \app\admin\model\payment\Channel::where('id',$payinfo['channel_id'])->find();
    	$yee= \app\admin\model\Yee::where('store_no',$store_no)->find();
    	    if($channel['code'] == 'sandPay'&&($payType == 'marchant_scan'||$payType == 'pos'))
    		{
    			    $jsonResp ='';
    			    if($payType=='marchant_scan')$jsonResp = $this->channelsandscan($osn,$total_amount,$payWay,$authcode);
    			    if($payType=='pos')$jsonResp = $this->channelsandpos($osn,$total_amount,$payWay,$authcode);
    		
			        if(isset($jsonResp['code']) && $jsonResp['code'] == '200'&&$payType=='marchant_scan')
			        {
			        	$data = json_decode($jsonResp['data'], JSON_UNESCAPED_UNICODE);
			        	
			        	if($data['sub_code'] == 'FAILED') $this->error('支付失败');
			        	$res = [];
                        if($data['sub_code'] == 'WAITING_PAYMENT' || $data['sub_code'] == 'SUCCESS')
                        {
                        	$is_pay = 0;
                        	if($data['sub_code'] == 'SUCCESS')$is_pay = 2;
                        	$channel = 'sandPay';
                        	$this->insertgoods($store_no,$user_id,$osn,$gasamount,$goodsamount,$is_pay,$pay,$gaslist,$goodslist,$total_amount,$paywayint,$channel,$gas_id,$gas_gun_id,$discount_price);
                        	if($sta_id)Guadan::where('id',$sta_id)->delete();
                        }
                        $res['out_order_no']=$data['out_order_no'];
                        $res['sub_code']=$data['sub_code'];
                        if($data['sub_code'] == 'SUCCESS')$this->eightprint($osn,$store_no);
			            $this->success($data['sub_code'],'',$res);
			        }
			        if(isset($jsonResp['code']) && $jsonResp['code'] == '0'&& $jsonResp['msg'] == 'success'&&$payType=='pos')
			        {
			        	if($jsonResp['data']['orderStatus'] == '待退款' || $jsonResp['data']['orderStatus'] == '已退款' ||$jsonResp['data']['orderStatus'] == '已撤回' ||$jsonResp['data']['orderStatus'] == '已失效') $this->error('支付失败');
			        	$res = [];
                        if($jsonResp['data']['orderStatus'] == '待收款' || $jsonResp['data']['orderStatus'] == '已支付')
                        {
                        	$is_pay = 0;
                        	if($jsonResp['data']['orderStatus'] == '已支付')$is_pay = 2;
                        	$channel = 'sandPay';
                        	$this->insertgoods($store_no,$user_id,$osn,$gasamount,$goodsamount,$is_pay,$pay,$gaslist,$goodslist,$total_amount,$paywayint,$channel,$gas_id,$gas_gun_id,$discount_price);
                        	if($sta_id)Guadan::where('id',$sta_id)->delete();
                        }
                        if($jsonResp['data']['orderStatus'] == '待收款')$jsonResp['data']['orderStatus'] = 'WAITING_PAYMENT';
 						if($jsonResp['data']['orderStatus'] == '已支付')$jsonResp['data']['orderStatus'] = 'SUCCESS';
                        $res['out_order_no']=$jsonResp['data']['merOrderNum'];
                        $res['sub_code']=$jsonResp['data']['orderStatus'];
                        
                        Order::where('order_no', $jsonResp['data']['merOrderNum'])->update(['ordernum'=>$jsonResp['data']['orderNum']]);
		        		Ordergas::where('order_no', $jsonResp['data']['merOrderNum'])->update(['ordernum'=>$jsonResp['data']['orderNum']]);
		        		Ordergoods::where('order_no', $jsonResp['data']['merOrderNum'])->update(['ordernum'=>$jsonResp['data']['orderNum']]);
		        		Orderrecharge::where('order_no', $jsonResp['data']['merOrderNum'])->update(['ordernum'=>$jsonResp['data']['orderNum']]);
		        		if($jsonResp['data']['orderStatus'] == '已支付')$this->eightprint($osn,$store_no);
			            $this->success($jsonResp['data']['orderStatus'],'',$res);
			        }
		            $this->error('支付失败');
			        
    		}
    		if($channel['code'] == 'YeeBao'&&($payType == 'marchant_scan'||$payType == 'pos'))
    		{
    			    if($payType=='marchant_scan')$response = $this->channelyeescan($yee,$osn,$total_amount,$payWay,$authcode);
			        if($payType=='pos')$response = $this->channelyeespos($yee,$osn,$total_amount,$payWay,$authcode);
	
			        if(isset($response->result->code) && $response->result->code == '00000'&&$payType=='marchant_scan')
			        {
			        	if($response->result->status == 'FAIL') $this->error('支付失败');
			        	$res = [];
			        	if($response->result->status == 'WAITPAY' || $response->result->status == 'SUCCESS')
                        {
                        	
                        	$is_pay = 0;
                        	if($response->result->status == 'SUCCESS')$is_pay = 2;
                        	if($response->result->status == 'WAITPAY')
                        	{
                        		$response->result->status = 'WAITING_PAYMENT';
                        	}
                        	$channel = 'YeeBao';
                        	$this->insertgoods($store_no,$user_id,$osn,$gasamount,$goodsamount,$is_pay,$pay,$gaslist,$goodslist,$total_amount,$paywayint,$channel,$gas_id,$gas_gun_id,$discount_price);
                        	if($sta_id)Guadan::where('id',$sta_id)->delete();
                        	
                        }
                        $res['out_order_no']=$response->result->orderId;
                        $res['sub_code']=$response->result->status;
                        if($response->result->status == 'SUCCESS')$this->eightprint($osn,$store_no);
                        Order::where('order_no', $osn)->update(['ordernum'=>$response->result->uniqueOrderNo]);
		        		Ordergas::where('order_no', $osn)->update(['ordernum'=>$response->result->uniqueOrderNo]);
		        		Ordergoods::where('order_no', $osn)->update(['ordernum'=>$response->result->uniqueOrderNo]);
		        		Orderrecharge::where('order_no', $osn)->update(['ordernum'=>$response->result->uniqueOrderNo]);
			        	$this->success($response->result->status,'',$res);
			        }
			        if(isset($response->result->code) && $response->result->code == 'OPR00000'&&$payType=='pos')
			        {
			        	    $is_pay = 0;
                        	$channel = 'YeeBao';
                        	$this->insertgoods($store_no,$user_id,$osn,$gasamount,$goodsamount,$is_pay,$pay,$gaslist,$goodslist,$total_amount,$paywayint,$channel,$gas_id,$gas_gun_id,$discount_price);
                        	if($sta_id)Guadan::where('id',$sta_id)->delete();
                        	$res['out_order_no']=$response->result->orderId;
	                        $res['sub_code']='WAITING_PAYMENT';
	                        Order::where('order_no', $osn)->update(['ordernum'=>$response->result->uniqueOrderNo]);
			        		Ordergas::where('order_no', $osn)->update(['ordernum'=>$response->result->uniqueOrderNo]);
			        		Ordergoods::where('order_no', $osn)->update(['ordernum'=>$response->result->uniqueOrderNo]);
			        		Orderrecharge::where('order_no', $osn)->update(['ordernum'=>$response->result->uniqueOrderNo]);
				        	$this->success('WAITING_PAYMENT','',$res);
			        }
			        
                    $this->error('支付失败');
    		}

    		if($payType == 'cash')
    		{
    			$is_pay = 2;
    			$channel = $payType;
                $this->insertgoods($store_no,$user_id,$osn,$gasamount,$goodsamount,$is_pay,$pay,$gaslist,$goodslist,$total_amount,$paywayint,$channel,$gas_id,$gas_gun_id,$discount_price);
                $res['out_order_no']=$osn;
                $res['sub_code']='SUCCESS';
//              $this->printorder($osn,$store_no);
                $this->eightprint($osn,$store_no);
                $this->success('SUCCESS','',$res);
    		}

    	$this->success('请求成功','',$list);
    }
    public function channelsandscan($osn,$total_amount,$payWay,$authcode)
    {
    	           $user_info = Session::get('admin');//获取当前登录用户信息
    	           $sandmer = Sandmerch::where('store_no', $user_info['store_no'])->find();
    	  /*商户私钥*/
		           $request = new HmPayClient();

			        $url = $request->gatewayUrl;
			
			        $appId = '552021071325659';
			        $subAppId = $sandmer['sub_merchant_no'];
			        $method = "trade.pay";
			        $format = $request->format;
			        $charset = $request->charset;
			        $signType = $request->signType;
			        $version = $request->apiVersion;
			        $timestamp = date("Y-m-d h:i:s");
			        $nonce = $request->getRandStr(8);
			        $privateKey = $request->rsaPrivateKey;
			        //支付方式
			        $payWay = $payWay;
			        $createIp = $_SERVER['REMOTE_ADDR'];//生产环境使用真实ip
			        $createTime = date("YmdHis");
			        $expireTime = date("YmdHis", strtotime("+10 minute"));//过期时间
			        $totalAmount = $total_amount;
			        $outOrderNo = $osn;
			        //商品详情 -- 按实际填写 或不填不上送
			        $goodsDetail1 = array();
		
			        $goodsDetail = array($goodsDetail1);
			        //订单详情
			        $body = '收银台下单';
			        //商户交易门店
			        $storeId = $sandmer['sand_store_no'];
//			
			        $notifyUrl = 'https://store.leyinshuke.com/api/index/sandscannotify';
			
			        $bizContent = $request->tradepay($authcode ,$payWay, $createIp, $createTime,  $totalAmount, $outOrderNo, $goodsDetail, $body, $storeId, $notifyUrl);
			        
			        $response = $request->execute($url, $request->request($appId, $subAppId, $method, $format, $charset, $signType, $timestamp, $nonce, $version, $bizContent, $privateKey));
			        
			        $jsonResp = json_decode($response, JSON_UNESCAPED_UNICODE);
			        return $jsonResp;
    }
        public function channelsandpos($osn,$total_amount,$payWay,$authcode)
    {
    	
    	           $user_info = Session::get('admin');//获取当前登录用户信息
    	           $sandmer = Sandmerch::where('store_no', $user_info['store_no'])->find();
    	  /*商户私钥*/
		           $request = new PosHmPayClient();

			        $url = $request->gatewayUrl;
			        $signType = $request->signType;
			        $privateKey = $request->rsaPrivateKey;
			        $totalAmount = $total_amount;
			        $outOrderNo = $osn;
			        //商品详情 -- 按实际填写 或不填不上送
			          //商品详情 -- 按实际填写 或不填不上送
			        $goodsDetail1[] = array(
			          'title'=>'a01',
			          'content'=>'a01',
			        );

			        
			        $para = $request->posrequest($outOrderNo, $sandmer['pos_merchant_no'], $sandmer['term_sn'], $totalAmount, $goodsDetail1, $signType, $privateKey);
			        
			        $response = $request->execute($url,$para);
			        
			        $jsonResp = json_decode($response, JSON_UNESCAPED_UNICODE);
			        return $jsonResp;
    }
    public function channelyeescan($yee,$osn,$total_amount,$payWay,$authcode)
    {
    	  /*商户私钥*/
			        $private_key ="MIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAQCQMqL/T97RhAophQNRzBwE+vU+59PzfkEzyLZwMaQTduHvdTl4fg6KZ6ATFUgECI2JLpZq3cyjVYSlM9H20bRpZSaoYmsYyNibpf2lg+bMg9G+bS6elHvFn0ZJ+aU40wyWqPjtdLB9JYLDbLVsb6SzHegWovWeWD7vUqCbPhDK24V///baX2zV4609kfa1iBGbynF/0nggHw3leeUW9F8E8twSEF15ObE8ShywOMvi578kv9PUNmSiq8gfc/t8dWVOzi4mbDje49MhxMbuopGv1kcvHBrThTeqQ2plhQSs63AbwLpe4WsZbcNvG9zpjuci8bK1+Zb/3DnkmT4zEu6FAgMBAAECggEAHsQfEPhaoztX67nslmRFSi69atmN2HMEuGbHvjJpPpnr5OqPA41pztADUG8G+Y1VnYJqJ40BX4wcjB79Wnst0hr53414KkaYKMWG0+zLrrElbErhWoZ1zhmIprn0LaaiFfchfZCbI2iAeO/V2bgMXQcxgLruSwWrD+cCS303mgBgW7tWsqlfplLvtWqJBWyA4Y8ObV/RUuLjr38Q8nCGZ81ep+De0euDkV4JQ/tg7uQEvEAOwpB6EEBwYt8GZVwcq8SWfP1cOw0Q7hkvn+rHvnXa2MHg8pdQHOfigvHr4Z5udkSiM885Pbjyh6H+UldtKFx2pW9EoD4t37CMwjeJtQKBgQDMWc00sfln9lRUBarV0D7fL6Z8/kueyBaTXFrzauHGwqK9KvB9ADmqFuBxZij8fJBkQyQtgNgbutTqgo0BJgTB2Q5lH097SBUdrTUrJdo3+rKY4/fbQBU7zF9oQ2p+dyFHmW/zjjWALnQYchd1lsZGkrSg2qPto/PRttkES/jrywKBgQC0pLrjcQ+6XZAUie+wSML+f/zGvxw1821Tn8poe0FIaX7/vPhRo028eF+R4Kav/yiVxeTAzk1D5OtN0Q3XO/nIY6f68WbdjBeFFSyovpPi1GX8kSys5wIo79nNnF/cEIJMTnvmyn51RaH8jtSVhshqqzHdesezXTYV3lwg4Urk7wKBgFqKS0ZWuIdcd76GiEuVqdWfOifVT9H5Gy+NUurY51H2OL6RwN3RdLssyaLUvcIoup0BtozGsnmOzPlegHUK0D7HGf6p4cBgjqKIdK86ZTY6SFk/YDjvarkE8xyyCgQgaklb7WM/FetGKcAPBN/fvtfT9l3yoYEQDF5Vok+qDY8DAn80N2nOVOA2/tSnGzgtvNqgtl5bFOMStUrk4Uug5//27ofHZNhiwNG3qRP3FvkX5qnUoV9+XCP5fDKIS+W0UaHiSuxDnYQehmBGF9jQ7kXRS5Qvbcd8M0psiuhqhsku05bWd9lY3S+wtnAckSziDBPiwZmoa9VOA6Oerqfy2SzNAoGAETFFK7YKO6+fGNJv5M5KJuZsOGkqgmfkJhAOnC2wLPDMMFDXnWG+oPcI6bosyvM+I8FDqwE3VcbmFlEJPnC4hQvwK3JjAju6FGhDgoB98rihcaUlsJfoTvrSmkLAmQOH8DW+a0UVbcCMp7TtWgpC8UMT0adAb/4ngQhjYuED4pI=";
			
			        $request = new YopRequest("app_10088909942", $private_key);
			        $expireTime = date("yyyy-MM-dd HH:mm:ss", strtotime("+30 minute"));//过期时间
			        $client_ip = $_SERVER['REMOTE_ADDR'];
			        //加入请求参数
			        $request->addParam("parentMerchantNo",'10088970121');
			        $request->addParam("merchantNo",$yee['merchantNo']);
			        $request->addParam("orderId",$osn);
			        $request->addParam("orderAmount",$total_amount);
			        $request->addParam("expiredTime",$expireTime);
			        $request->addParam("notifyUrl",'https://store.leyinshuke.com/api/index/yeenotify');
			        $request->addParam("memo",'');
			        $request->addParam("goodsName",'收银台下单');
			        $request->addParam("fundProcessType",'DELAY_SETTLE');
			        $request->addParam("payWay",'MERCHANT_SCAN');
			        $request->addParam("channel", $payWay);
			        $request->addParam("scene", 'OFFLINE');
			        $request->addParam("authCode", $authcode);
			        $request->addParam("terminalId", "00000000");
			        $request->addParam("userIp", $client_ip);
			//      //提交Post请求
			        $response = YopRsaClient::post("/rest/v1.0/aggpay/pay", $request);
			        return $response;
    }
    public function channelyeespos($yee,$osn,$total_amount,$payWay,$authcode)
    {
    	 $user_info = Session::get('admin');//获取当前登录用户信息
    	 $yeepos= \app\admin\model\Yeepos::where('store_no',$user_info['store_no'])->find();
    	  /*商户私钥*/
			        $private_key ="MIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAQCQMqL/T97RhAophQNRzBwE+vU+59PzfkEzyLZwMaQTduHvdTl4fg6KZ6ATFUgECI2JLpZq3cyjVYSlM9H20bRpZSaoYmsYyNibpf2lg+bMg9G+bS6elHvFn0ZJ+aU40wyWqPjtdLB9JYLDbLVsb6SzHegWovWeWD7vUqCbPhDK24V///baX2zV4609kfa1iBGbynF/0nggHw3leeUW9F8E8twSEF15ObE8ShywOMvi578kv9PUNmSiq8gfc/t8dWVOzi4mbDje49MhxMbuopGv1kcvHBrThTeqQ2plhQSs63AbwLpe4WsZbcNvG9zpjuci8bK1+Zb/3DnkmT4zEu6FAgMBAAECggEAHsQfEPhaoztX67nslmRFSi69atmN2HMEuGbHvjJpPpnr5OqPA41pztADUG8G+Y1VnYJqJ40BX4wcjB79Wnst0hr53414KkaYKMWG0+zLrrElbErhWoZ1zhmIprn0LaaiFfchfZCbI2iAeO/V2bgMXQcxgLruSwWrD+cCS303mgBgW7tWsqlfplLvtWqJBWyA4Y8ObV/RUuLjr38Q8nCGZ81ep+De0euDkV4JQ/tg7uQEvEAOwpB6EEBwYt8GZVwcq8SWfP1cOw0Q7hkvn+rHvnXa2MHg8pdQHOfigvHr4Z5udkSiM885Pbjyh6H+UldtKFx2pW9EoD4t37CMwjeJtQKBgQDMWc00sfln9lRUBarV0D7fL6Z8/kueyBaTXFrzauHGwqK9KvB9ADmqFuBxZij8fJBkQyQtgNgbutTqgo0BJgTB2Q5lH097SBUdrTUrJdo3+rKY4/fbQBU7zF9oQ2p+dyFHmW/zjjWALnQYchd1lsZGkrSg2qPto/PRttkES/jrywKBgQC0pLrjcQ+6XZAUie+wSML+f/zGvxw1821Tn8poe0FIaX7/vPhRo028eF+R4Kav/yiVxeTAzk1D5OtN0Q3XO/nIY6f68WbdjBeFFSyovpPi1GX8kSys5wIo79nNnF/cEIJMTnvmyn51RaH8jtSVhshqqzHdesezXTYV3lwg4Urk7wKBgFqKS0ZWuIdcd76GiEuVqdWfOifVT9H5Gy+NUurY51H2OL6RwN3RdLssyaLUvcIoup0BtozGsnmOzPlegHUK0D7HGf6p4cBgjqKIdK86ZTY6SFk/YDjvarkE8xyyCgQgaklb7WM/FetGKcAPBN/fvtfT9l3yoYEQDF5Vok+qDY8DAn80N2nOVOA2/tSnGzgtvNqgtl5bFOMStUrk4Uug5//27ofHZNhiwNG3qRP3FvkX5qnUoV9+XCP5fDKIS+W0UaHiSuxDnYQehmBGF9jQ7kXRS5Qvbcd8M0psiuhqhsku05bWd9lY3S+wtnAckSziDBPiwZmoa9VOA6Oerqfy2SzNAoGAETFFK7YKO6+fGNJv5M5KJuZsOGkqgmfkJhAOnC2wLPDMMFDXnWG+oPcI6bosyvM+I8FDqwE3VcbmFlEJPnC4hQvwK3JjAju6FGhDgoB98rihcaUlsJfoTvrSmkLAmQOH8DW+a0UVbcCMp7TtWgpC8UMT0adAb/4ngQhjYuED4pI=";
			
			        $request = new YopRequest("app_10088909942", $private_key);
			        $expireTime = date("yyyy-MM-dd HH:mm:ss", strtotime("+30 minute"));//过期时间
			        $client_ip = $_SERVER['REMOTE_ADDR'];
			        
			        $terminalInfo = array(
			                'terminalNo'   => $yeepos['terminal_sn'] ?? '',
			                'terminalType' => 'POS',
			            );     
			        $terminalInfo = json_encode($terminalInfo);
			        //加入请求参数
			        $request->addParam("parentMerchantNo",'10088970121');
			        $request->addParam("merchantNo",$yee['merchantNo']);
			        $request->addParam("orderId",$osn);
			        $request->addParam("orderAmount",$total_amount);
			        $request->addParam("fundProcessType",'DELAY_SETTLE');
//			        $request->addParam("expiredTime",$expireTime);
			        $request->addParam("notifyUrl",'https://store.leyinshuke.com/api/index/yeenotify');
			        $request->addParam("memo",'');
			        $request->addParam("goodsName",'收银台下单');
			        $request->addParam("terminalInfo",$terminalInfo);
//			        $request->addParam("channel", $payWay);
//			        $request->addParam("scene", 'OFFLINE');
//			        $request->addParam("authCode", $authcode);
//			        $request->addParam("terminalId", "00000000");
//			        $request->addParam("userIp", $client_ip);
			//      //提交Post请求
			        $response = YopRsaClient::post("/rest/v1.0/trade/order", $request);
			        return $response;
    }
    public function insertgoods($store_no,$user_id,$osn,$gasamount,$goodsamount,$is_pay,$pay,$gaslist,$goodslist,$total_amount,$paywayint,$channel,$gas_id,$gas_gun_id,$discount_price)
    {
                            $stainfo = Station::where('store_no', $store_no)->find();
                            $total_all = $gasamount+$goodsamount;
                        	if($gasamount>0)
                        	{
                        		$paramgas['agent_id']=$stainfo['agent_id'];
                        		$paramgas['store_no']=$store_no;
						        $paramgas['user_id']=$user_id;
						        $paramgas['order_no']=$osn;
						        $paramgas['total_price']=$gasamount;
						        $paramgas['total_pay_price']=$gasamount;
						        $paramgas['discount_price']=$discount_price;
						        $paramgas['is_pay']=$is_pay;
						        $paramgas['pay_type']=$pay;
						        $paramgas['pay_way']=$paywayint;
						        $paramgas['pay_time']=time();
						        $paramgas['source_type']=2;
						        $paramgas['channel']=$channel;
					    		$resultgas = Ordergas::create($paramgas);
					    		if($resultgas)
					    		{
//                                 if($gaslist)
//                                 {
//                                 	   foreach ($gaslist as $k => $v) {
                                   	   	
                                   	   		$oil = Gasset::where('id',$gas_id)->find();
    										$gasnum = round($gasamount/$oil['price'],2);
                                   	   		//油品详情
                                   	   		$paraminfo['agent_id']=$stainfo['agent_id'];
									        $paraminfo['store_no']=$store_no;
									        $paraminfo['order_id']=$resultgas['id'];
									        $paraminfo['gas_gun_id']=$gas_gun_id;
									        $paraminfo['num']=$gasnum;
									        $paraminfo['unit_price']=$oil['price'];
									        $paraminfo['total_price']=$gasamount;
									        $paraminfo['unit']=$oil['unit'];
								    		$resultinfo = OrderGasInfo::create($paraminfo);
								    		//扣减油品库存
								    		$gun = Gasgun::where('id',$gas_gun_id)->find();
								    		Gasoil::where('id', $gun['oil_id'])->setDec('oil_num', $gasnum);
								    		//删除购物车
									        Pcgascart::where('store_no',$store_no)->delete();
//                                 	   }
//                                 }

					    		}
                        	}
                        	
                        	if($goodsamount>0)
                        	{
                        		$paramgood['agent_id']=$stainfo['agent_id'];
                        		$paramgood['store_no']=$store_no;
						        $paramgood['user_id']=$user_id;
						        $paramgood['order_no']=$osn;
						        $paramgood['total_price']=$goodsamount;
						        $paramgood['total_pay_price']=$goodsamount;
						        $paramgood['discount_price']=0;
						        $paramgood['is_pay']=$is_pay;
						        $paramgood['pay_type']=$pay;
						        $paramgood['pay_time']=time();
						        $paramgood['source_type']=2;
						        $paramgood['pay_way']=$paywayint;
						        $paramgood['channel']=$channel;
					    		$resultgood = Ordergoods::create($paramgood);
					    		if($resultgood)
					    		{
					    	        if($goodslist)
					    	        {
					    	        	foreach ($goodslist as $in => $it) {
					    	        		$goodone = Goods::where('id',$it['goods_id'])->find();
					    					if(!$goodone)continue;
					    				
						    	        	//订单详情
						    	        	$paramgoodsinfo['agent_id']=$stainfo['agent_id'];
									        $paramgoodsinfo['store_no']=$store_no;
									        $paramgoodsinfo['order_id']=$resultgood['id'];
									        $paramgoodsinfo['goods_id']=$it['goods_id'];
									        $paramgoodsinfo['num']=$it['num'];
									        $paramgoodsinfo['unit_price']=$it['price'];
									        $paramgoodsinfo['total_price']=$it['price']*$it['num'];
									        $paramgoodsinfo['goods_sku']=$goodone['sku'];
							
								    		$resultinfo = OrderGoodsInfo::create($paramgoodsinfo);
								    		
								    		//扣减商品库存
					
									        Goods::where('id', $it['goods_id'])->setDec('goods_stock', $it['num']);
									        
									        //删除购物车
									        Pccart::where('id',$it['id'])->where('store_no',$store_no)->delete();
							    		}
					    	        }
					    		}
                        	}
                        	
                        	//录入总订单
                        	$params['agent_id']=$stainfo['agent_id'];
					        $params['store_no']=$store_no;
					        $params['user_id']=$user_id;
					        $params['order_no']=$osn;
					        $params['total_price']=$total_all;
					        $params['total_pay_price']=$total_amount;
					        $params['discount_price']=$discount_price;
					        $params['is_pay']=$is_pay;
					        $params['pay_type']=$pay;
					        $params['type']=4;
					        $params['source_type']=2;
					        $params['pay_time']=time();
					        $params['pay_way']=$paywayint;
					        $params['channel']=$channel;
					    	$result = Order::create($params);
    }
    
    
    
                  /**
     *查询订单支付结果
     * 
     *
     */
    public function search_order()
    {
    	$user_info = Session::get('admin');//获取当前登录用户信息
    	$this->agent_id = $user_info['agent_id'];
    	$this->admin_id = $user_info['id'];
        $store_no = $user_info['store_no'];
        $out_order_no = $this->request->request("out_order_no");
//  	$store_no = 1;
    	$order = Order::where('order_no', $out_order_no)->find();
    	$yee= \app\admin\model\Yee::where('store_no',$store_no)->find();

    	if($order['is_pay'] == 2)
    	{
    		$this->eightprint($out_order_no,$store_no);
    		$payres['out_order_no']=$out_order_no;
            $payres['sub_code']='SUCCESS';
			$this->success('SUCCESS','',$payres);
    	}
    	if(!$order)$this->error('订单无效');
   
    	    if($order['channel'] == 'sandPay'&&$order['pay_way'] != 3)
    		{
    			    $jsonResp ='';
    			    $jsonResp = $this->channelsearchorder($out_order_no,$order['createtime']);
    			
			        if(isset($jsonResp['code']) && $jsonResp['code'] == '200')
			        {
			        	$data = json_decode($jsonResp['data'], JSON_UNESCAPED_UNICODE);
			        	if($data['sub_code'] == 'FAILED') $this->error('支付失败');
			        	$res = [];
                        if($data['sub_code'] == 'SUCCESS')
                        {
                            Order::where('order_no', $out_order_no)->update(['is_pay' => 2,'ordernum'=>$data['plat_trx_no'],'bank_no'=>$data['bank_order_no']]);
                            Ordergas::where('order_no', $out_order_no)->update(['is_pay'=>2,'ordernum'=>$data['plat_trx_no'],'bank_no'=>$data['bank_order_no']]);
        			        Ordergoods::where('order_no', $out_order_no)->update(['is_pay'=>2,'ordernum'=>$data['plat_trx_no'],'bank_no'=>$data['bank_order_no']]);
        			        $this->eightprint($out_order_no,$store_no);
                        }
                        $res['out_order_no']=$out_order_no;
                        $res['sub_code']=$data['sub_code'];
			            $this->success($data['sub_code'],'',$res);
			        }
		            $this->error('支付失败');
			        
    		}
    		 if($order['channel'] == 'sandPay'&&$order['pay_way'] == 3)
    		{
    			    $jsonResp ='';
    			    $jsonResp = $this->channelpossearchorder($out_order_no,$order['createtime']);
			        if(isset($jsonResp['code']) && $jsonResp['code'] == '0'&& $jsonResp['msg'] == 'success')
			        {
			        	if($jsonResp['data']['orderStatus'] == '已支付')
                        {
                        	$type = 3;
					    	if($jsonResp['data']['payType'] == "03")$type = 1;
					    	if($jsonResp['data']['payType'] == "04")$type = 2;
                            Order::where('order_no', $out_order_no)->update(['is_pay' => 2,'bank_no'=>$jsonResp['data']['notice']['orderNumber'],'pay_type' => $type]);
                            Ordergas::where('order_no', $out_order_no)->update(['is_pay'=>2,'bank_no'=>$jsonResp['data']['notice']['orderNumber'],'pay_type' => $type]);
        			        Ordergoods::where('order_no', $out_order_no)->update(['is_pay'=>2,'bank_no'=>$jsonResp['data']['notice']['orderNumber'],'pay_type' => $type]);
        			        $this->eightprint($out_order_no,$store_no);
                        }
                        if($jsonResp['data']['orderStatus'] == '待收款')$jsonResp['data']['orderStatus'] = 'WAITING_PAYMENT';
 						if($jsonResp['data']['orderStatus'] == '已支付')$jsonResp['data']['orderStatus'] = 'SUCCESS';
                        $res['out_order_no']=$out_order_no;
                        $res['sub_code']=$jsonResp['data']['orderStatus'];
			            $this->success($jsonResp['data']['orderStatus'],'',$res);
			        }
		            $this->error('支付失败');
			        
    		}
    		if($order['channel'] == 'YeeBao')
    		{
    			    $response = $this->channelyeessearchorder($yee,$out_order_no);
	
			        if(isset($response->result->code) && $response->result->code == 'OPR00000')
			        {
			        	if($response->result->status == 'FAIL' || $response->result->status == 'CLOSE' || $response->result->status == 'TIME_OUT') $this->error('支付失败');
			        	$res = [];
			        	if($response->result->status == 'SUCCESS')
                        {
                        	Order::where('order_no', $out_order_no)->update(['is_pay' => 2]);
                            Ordergas::where('order_no', $out_order_no)->update(['is_pay'=>2]);
        			        Ordergoods::where('order_no', $out_order_no)->update(['is_pay'=>2]);
        			        $this->eightprint($out_order_no,$store_no);
                        }
                        if($response->result->status == 'PROCESSING')$response->result->status = 'WAITING_PAYMENT';
                        $res['out_order_no']=$response->result->orderId;
                        $res['sub_code']=$response->result->status;
			        	$this->success($response->result->status,'',$res);
			        }
                    $this->error('支付失败');
    		}

    	$this->error('支付失败');
    }
    
    public function channelsearchorder($osn,$createTime)
    {
    				$user_info = Session::get('admin');//获取当前登录用户信息
    	           $sandmer = Sandmerch::where('store_no', $user_info['store_no'])->find();
    	  /*商户私钥*/
		           $request = new HmPayClient();

			        $url = $request->gatewayUrl;
			
			        $appId = '552021071325659';
			        $subAppId = $sandmer['sub_merchant_no'];
			        $method = "trade.query";
			        $format = $request->format;
			        $charset = $request->charset;
			        $signType = $request->signType;
			        $version = $request->apiVersion;
			        $timestamp = date("Y-m-d h:i:s");
			        $nonce = $request->getRandStr(8);
			        $privateKey = $request->rsaPrivateKey;
			        //支付方式
		
			        $createIp = $_SERVER['REMOTE_ADDR'];//生产环境使用真实ip
			        $createTime = date("YmdHis",$createTime);
			        $expireTime = date("YmdHis", $createTime);//过期时间
	
			        $outOrderNo = $osn;
			        //商户交易门店
			        $storeId = $sandmer['sand_store_no'];

			
			        $bizContent = $request->tradequery($createTime,$outOrderNo);
			        
			        $response = $request->execute($url, $request->request($appId, $subAppId, $method, $format, $charset, $signType, $timestamp, $nonce, $version, $bizContent, $privateKey));
			        
			        $jsonResp = json_decode($response, JSON_UNESCAPED_UNICODE);
			        return $jsonResp;
    }
    public function channelpossearchorder($osn,$createTime)
    {
    	
    	           $user_info = Session::get('admin');//获取当前登录用户信息
    	           $sandmer = Sandmerch::where('store_no', 1)->find();
    	  /*商户私钥*/
		           $request = new PosHmPayClient();

			        $url = "https://pos.hmpay.com.cn/sandpos/merchantApi/detail";
			        $signType = $request->signType;
			        $privateKey = $request->rsaPrivateKey;
			        $outOrderNo = $osn;

			        
			        $para = $request->searchrequest($outOrderNo, $sandmer['pos_merchant_no'],$signType, $privateKey);
			        
			        $response = $request->execute($url,$para);
			        
			        $jsonResp = json_decode($response, JSON_UNESCAPED_UNICODE);
			        return $jsonResp;
    }
    public function channelyeessearchorder($yee,$osn)
    {
    	  /*商户私钥*/
			        $private_key ="MIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAQCQMqL/T97RhAophQNRzBwE+vU+59PzfkEzyLZwMaQTduHvdTl4fg6KZ6ATFUgECI2JLpZq3cyjVYSlM9H20bRpZSaoYmsYyNibpf2lg+bMg9G+bS6elHvFn0ZJ+aU40wyWqPjtdLB9JYLDbLVsb6SzHegWovWeWD7vUqCbPhDK24V///baX2zV4609kfa1iBGbynF/0nggHw3leeUW9F8E8twSEF15ObE8ShywOMvi578kv9PUNmSiq8gfc/t8dWVOzi4mbDje49MhxMbuopGv1kcvHBrThTeqQ2plhQSs63AbwLpe4WsZbcNvG9zpjuci8bK1+Zb/3DnkmT4zEu6FAgMBAAECggEAHsQfEPhaoztX67nslmRFSi69atmN2HMEuGbHvjJpPpnr5OqPA41pztADUG8G+Y1VnYJqJ40BX4wcjB79Wnst0hr53414KkaYKMWG0+zLrrElbErhWoZ1zhmIprn0LaaiFfchfZCbI2iAeO/V2bgMXQcxgLruSwWrD+cCS303mgBgW7tWsqlfplLvtWqJBWyA4Y8ObV/RUuLjr38Q8nCGZ81ep+De0euDkV4JQ/tg7uQEvEAOwpB6EEBwYt8GZVwcq8SWfP1cOw0Q7hkvn+rHvnXa2MHg8pdQHOfigvHr4Z5udkSiM885Pbjyh6H+UldtKFx2pW9EoD4t37CMwjeJtQKBgQDMWc00sfln9lRUBarV0D7fL6Z8/kueyBaTXFrzauHGwqK9KvB9ADmqFuBxZij8fJBkQyQtgNgbutTqgo0BJgTB2Q5lH097SBUdrTUrJdo3+rKY4/fbQBU7zF9oQ2p+dyFHmW/zjjWALnQYchd1lsZGkrSg2qPto/PRttkES/jrywKBgQC0pLrjcQ+6XZAUie+wSML+f/zGvxw1821Tn8poe0FIaX7/vPhRo028eF+R4Kav/yiVxeTAzk1D5OtN0Q3XO/nIY6f68WbdjBeFFSyovpPi1GX8kSys5wIo79nNnF/cEIJMTnvmyn51RaH8jtSVhshqqzHdesezXTYV3lwg4Urk7wKBgFqKS0ZWuIdcd76GiEuVqdWfOifVT9H5Gy+NUurY51H2OL6RwN3RdLssyaLUvcIoup0BtozGsnmOzPlegHUK0D7HGf6p4cBgjqKIdK86ZTY6SFk/YDjvarkE8xyyCgQgaklb7WM/FetGKcAPBN/fvtfT9l3yoYEQDF5Vok+qDY8DAn80N2nOVOA2/tSnGzgtvNqgtl5bFOMStUrk4Uug5//27ofHZNhiwNG3qRP3FvkX5qnUoV9+XCP5fDKIS+W0UaHiSuxDnYQehmBGF9jQ7kXRS5Qvbcd8M0psiuhqhsku05bWd9lY3S+wtnAckSziDBPiwZmoa9VOA6Oerqfy2SzNAoGAETFFK7YKO6+fGNJv5M5KJuZsOGkqgmfkJhAOnC2wLPDMMFDXnWG+oPcI6bosyvM+I8FDqwE3VcbmFlEJPnC4hQvwK3JjAju6FGhDgoB98rihcaUlsJfoTvrSmkLAmQOH8DW+a0UVbcCMp7TtWgpC8UMT0adAb/4ngQhjYuED4pI=";
			
			        $request = new YopRequest("app_10088909942", $private_key);
			        $expireTime = date("yyyy-MM-dd HH:mm:ss", strtotime("+30 minute"));//过期时间
			        $client_ip = $_SERVER['REMOTE_ADDR'];
			        //加入请求参数
			        $request->addParam("parentMerchantNo",'10088970121');
			        $request->addParam("merchantNo",$yee['merchantNo']);
			        $request->addParam("orderId",$osn);

			//      //提交Post请求
			        $response = YopRsaClient::get("/rest/v1.0/trade/order/query", $request);
			        return $response;
    }
    
    public function printorder($osn,$store_no)
    {
    	$order = Order::where('order_no', $osn)->find();
        $ordergas = Ordergas::where('order_no', $osn)->find();
        $ordergoods = Ordergoods::where('order_no', $osn)->find();
        $ordergasinfo = OrderGasInfo::where('order_id', $ordergas['id'])->select();
        $ordergoodsinfo = OrderGoodsInfo::where('order_id', $ordergoods['id'])->select();
        $print = Printer::where('store_no', $store_no)->find();
        $storeset = Storeset::where('store_no', $store_no)->find();
        $config = new YlyConfig('1056778478', '52dc0ea2e501aae12e3fbd59dc59c631');

		$client = new YlyOauthClient($config);
		$token = $client->getToken();   //若是开放型应用请传授权码code
		
		$printer = new PrinterService($token->access_token, $config);
		$data = $printer->addPrinter($print['terminal_no'], $print['secret'], '', '');
		
		$print = new PrintService($token->access_token, $config);
//		$data = $print->index('4004818534','打印内容排版可看Demo下的callback.php','你的系统内部id自定义32位以内');
		/**文本接口开始**/
//		$print = new PrintService($access_token, $config);
		//58mm排版 排版指令详情请看 http://doc2.10ss.net/332006
		$content = "<FS2><center>**#".$order['id']." 加油站**</center></FS2>";
		$content .= str_repeat('.', 32);
		$content .= "<FS2><center>--在线支付--</center></FS2>";
		$content .= "<FS><center>".$storeset['store_name']."</center></FS>";
		$content .= "订单时间:". date("Y-m-d H:i") . "\n";
		$content .= "订单编号:".$osn."\n";
		if($ordergoodsinfo)
		{
			$content .= str_repeat('*', 14) . "商品" . str_repeat("*", 14);
			$content .= "<table>";
			foreach ($ordergoodsinfo as $in => $it) {
				$goodinfo = Goods::where('id', $it['goods_id'])->find();
			    $content .= "<tr><td>".$goodinfo['goods_name']."</td><td>x".$it['num']."</td><td>".$it['unit_price']."</td></tr>";
            }
			$content .= "</table>";
		}
		if($ordergasinfo)
		{
			$content .= str_repeat('*', 14) . "油品" . str_repeat("*", 14);
			$content .= "<table>";
			foreach ($ordergasinfo as $k => $v) {
				$guninfo = Gasgun::where('id', $v['gas_gun_id'])->find();
				$guninfo = Gasset::where('id', $guninfo['gas_gun_id'])->find();
			    $content .= "<tr><td>".$goodinfo['goods_name']."</td><td>x".$v['num']."L</td><td>".$v['unit_price']."</td></tr>";
            }
			$content .= "</table>";
		}
		
		$content .= str_repeat('.', 32);
		$content .= "<QR></QR>";
		$content .= "小计:￥".$order['total_pay_price']."\n";
		$content .= "折扣:￥0 \n";
		$content .= str_repeat('*', 32);
		$content .= "订单总价:￥".$order['total_pay_price']."\n";
		$content .= "<FS2><center>**#".$order['id']." 完**</center></FS2>";
		$data = $print->index($print['terminal_no'], $content,$osn);
    }
    public function eightprint($osn,$store_no)
    {
    	        /**
         * <BR>：换行符（同一行有闭合标签(如 </C>)则应放到闭合标签前面, 连续两个换行符<BR><BR>可以表示加一空行）
         *  <L></L>：左对齐
         *  <C></C>：居中对齐
         *  <R></R>：右对齐
         *  注意：同一行内容不能使用多种对齐方式，可通过补空格方式自定义对齐样式。
         *       58mm的机器，一行打印16个汉字，32个字母
         *       80mm的机器，一行打印24个汉字，48个字母
         *
         *  <N></N>：字体正常大小
         *  <HB></HB>：字体变高一倍
         *  <WB></WB>：字体变宽一倍
         *  <B></B>：字体放大一倍
         *  <CB></CB>：字体放大一倍居中
         *  <HB2></HB2>：字体变高二倍
         *  <WB2></WB2>：字体变宽二倍
         *  <B2></B2>：字体放大二倍
         *  <BOLD></BOLD>：字体加粗
         *  <IMG></IMG>：打印LOGO图片，需登录开放平台在【打印机管理=》设备管理】下通过设置LOGO功能进行上传。此处直接写入
         *             空标签, 如 <IMG></IMG> 即可, 具体可参考样例。
         *             图片宽度设置：可以通过 <IMG> 标签名称自定义，如 <IMG60> 表示宽度为60，相应的闭合标签 </IMG>
         *             不需要指定高度。<IMG> 标签不指定宽度默认为40，最小值为20，最大值为100
         *  <QR></QR>：二维码（标签内容是二维码值, 最大不能超过256个字符, 单个订单最多只能打印一个二维码）。
         *             二维码宽度设置：可以通过 <QR> 标签名称自定义，如 <QR180> 表示宽度为180，相应的闭合标签 </QR>
         *             不需要指定宽度。<QR> 标签不指定宽度默认为110，最小值为90，最大值为180
         *  <BARCODE></BARCODE>：条形码（标签内容是条形码值）
         */
//      $store_no = 1;
//      $osn = "2023020915430674623773";
        $storeinfo = Storeset::where('store_no',$store_no)->find();
        $order = Order::where('order_no', $osn)->find();
        $ordergas = Ordergas::where('order_no', $osn)->find();
        $ordergoods = Ordergoods::where('order_no', $osn)->find();
        $ordergasinfo = OrderGasInfo::where('order_id', $ordergas['id'])->select();
        $ordergoodsinfo = OrderGoodsInfo::where('order_id', $ordergoods['id'])->select();
        $print = Printer::where('store_no', $store_no)->find();
        $printContent = "";

        $printContent = $printContent . "<C>" . "<B>".$storeinfo['store_name']."</B>" . "<BR></C>";
        $printContent = $printContent . "<BR>";
        if($ordergoodsinfo)
		{
	        $printContent = $printContent . "商品" . str_repeat(" ",15) . "数量" . str_repeat(" ", 2) . "单价" . str_repeat(" ", 2)
	            . "<BR>";
	        $printContent = $printContent . str_repeat("-", NoteFormatter::ROW_MAX_CHAR_LEN) . "<BR>";
	        foreach ($ordergoodsinfo as $in => $it) {	
	        	$goodinfo = Goods::where('id', $it['goods_id'])->find();
	            $printContent = $printContent . NoteFormatter::formatPrintOrderItem($goodinfo['goods_name'], $it['num'], $it['unit_price']);
	        }
	        $printContent = $printContent . str_repeat("-", NoteFormatter::ROW_MAX_CHAR_LEN) . "<BR>";
        }	
        if($ordergasinfo)
		{
	        $printContent = $printContent . "油品" . str_repeat(" ",15) . "数量" . str_repeat(" ", 2) . "单价" . str_repeat(" ", 2)
	            . "<BR>";
	        $printContent = $printContent . str_repeat("-", NoteFormatter::ROW_MAX_CHAR_LEN) . "<BR>";
	        foreach ($ordergasinfo as $k => $v) {
	        	$guninfo = Gasgun::where('id', $v['gas_gun_id'])->find();
				$gasinfo = Gasset::where('id', $guninfo['gas_id'])->find();
	            $printContent = $printContent . NoteFormatter::formatPrintOrderItem($gasinfo['gas_name'], $v['num'], $v['unit_price']);
	        }
	        $printContent = $printContent . str_repeat("-", NoteFormatter::ROW_MAX_CHAR_LEN) . "<BR>";
        }
        	
        $printContent = $printContent . "<R>" . "合计：" . $order['total_pay_price'] . "元" . "<BR></R>";

        $printContent = $printContent . "<BR>";
        $printContent = $printContent . "<L>"
//          . "客户地址：" . "珠海市香洲区xx路xx号" . "<BR>"
            . "订单编号：" . $osn . "<BR>"
            . "下单时间：" . date("Y-m-d H:i") . "<BR>";
//          . "备注：" . "少放辣 不吃香菜" . "<BR>";

        $printContent = $printContent . "<C>"
            . "<QR>https://www.xpyun.net</QR>"
            . "</C>";


        $request = new PrintRequest();
        $request->generateSign();

        //*必填*：打印机编号
        $request->sn = $print['terminal_no'];

        //*必填*：打印内容,不能超过12K
        $request->content = $printContent;

        //打印份数，默认为1
        $request->copies = 1;

        //声音播放模式，0 为取消订单模式，1 为静音模式，2 为来单播放模式，3为有用户申请退单了。默认为 2 来单播放模式
        $request->voice = 1;
        //打印模式：
        //值为 0 或不指定则会检查打印机是否在线，如果不在线 则不生成打印订单，直接返回设备不在线状态码；如果在线则生成打印订单，并返回打印订单号。
        //值为 1不检查打印机是否在线，直接生成打印订单，并返回打印订单号。如果打印机不在线，订单将缓存在打印队列中，打印机正常在线时会自动打印。
        $request->mode = 1;
        
        
        //支付方式：
        //取值范围41~55：
        //支付宝 41、微信 42、云支付 43、银联刷卡 44、银联支付 45、会员卡消费 46、会员卡充值 47、翼支付 48、成功收款 49、嘉联支付 50、壹钱包 51、京东支付 52、快钱支付 53、威支付 54、享钱支付 55
        //仅用于支持金额播报的芯烨云打印机。
        
        $paytype = 41;
        if($order['pay_type'] == 1)$paytype = 42;
        if($order['pay_type'] == 2)$paytype = 41;
        if($order['pay_type'] == 3)$paytype = 44;

        $request->payType = $paytype;

        //支付与否：
        //取值范围59~61：
        //退款 59 到账 60 消费 61。
        //仅用于支持金额播报的芯烨云打印机。
        $request->payMode = 60;

        //支付金额：
        //最多允许保留2位小数。
        //仅用于支持金额播报的芯烨云打印机。
        $request->money = $order['total_pay_price'] ;
        
        
        $service = new xpPrintService();
        $result = $service->xpYunPrint($request);
        if($order['pay_type'] == 5)$service->xpYunControlBox($request);
//      echo json_encode($request);
//        print $result->content->code . "\n";
//        print $result->content->msg . "\n";
//
//        //data:正确返回订单编号
//        print $result->content->data . "\n";
    }
    
    
                 /**
     *加油记录
     * 
     *
     */
    public function getoilorder()
    {
    	$user_info = Session::get('admin');//获取当前登录用户信息
    	$this->agent_id = $user_info['agent_id'];
        $store_no = $user_info['store_no'];
        $this->admin_id = $user_info['id'];
        $gasgun = $this->request->request("gasgun");

    
    	$list = Oilorder::where('store_no',$store_no)->where('status',0)->order('id desc')->select();
    	foreach ($list as $in => $it) {
    		$data = Gasgun::where('store_no', $store_no)->select();
    		$it['gas_id'] = '';
    		$it['gas_gun_id'] = '';
    		if($data)
    		{
    			foreach ($data as $index => $item) {
    			    if($it['gasgun'] == $this->findNum($item['name']))
    			    {
    			    	$it['gas_id'] = $item['gas_id'];
    		            $it['gas_gun_id'] = $item['id'];
    			    }
    			}
    		}
    		
    	}
    	
    	
    	$this->success('请求成功','',$list);
    	

        
    }
    public function findNum($str=”){
	    $str=trim($str);
    if(empty($str))return '';
			    $temp=array('1','2','3','4','5','6','7','8','9','0');
			    $result="";
			    for($i=0;$i<strlen($str);$i++){
			        if(in_array($str[$i],$temp)){
			            $result.=$str[$i];
			        }
			    }
			    return $result;
	}
}
